import Reflux from 'reflux';
import Actions from "./Actions";
import update from 'react-addons-update';

import DB from '../../../../app/db';
import StorageUtils from "../../../../app/storage";

const { API_URL} = require(`./../../../../config/${ENV}.json`);

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    userInfo: {},
    //小区信息
    court: {},
    // 委员
    nominations: [],
    // 选举任务状态
    rwStatus: [],
    // courtId
    cid: '',
    // 选举结果
    voteResult: {
      // 单元长
      dyz: [],
      // 楼栋长
      ldz: [],
      // 委员
      wy: [],
      // 主任
      zr: []
    },
    // 主任
    zr: {},
    modal: {
      visible: false,
      data: {}
    }
  },

  onInit(cid) {
    this.data.userInfo = update(this.data.userInfo, {$set: StorageUtils.getStorageItem('user')});
    this.data.cid = cid;
    this.updateComponent();
    this.initialData();
    this.getCourtById(cid);
    this.onTabsChange(0);
  },

  initialData() {
    this.data.voteResult = {
      // 单元长
      dyz: [],
      // 楼栋长
      ldz: [],
      // 委员
      wy: [],
      // 主任
      zr: []
    };
    this.data.court = {};
    this.data.nominations = [];
    this.data.rwStatus = [];
    this.updateComponent();
  },

  onTabsChange(index) {
    let t = this;
    switch(index) {
      case 0:
        this.getXjRwStatus(t.data.cid);
        break;
      case 1:
        let rw = t.data.rwStatus;
        if (rw && rw.length > 0) {
          rw.map( r => {
            if (r.over) {
              t.getMemberByRoleName(r.name);
            }
          })
        }
        break;
      case 2:
        this.getZr(t.data.cid);
        this.getWeiYuanButZr(t.data.cid);
        break;
      default:
        this.getXjRwStatus(t.data.cid);
        break;
    }
  },

  getMemberByRoleName(role) {
    let t = this;
    DB.ywh.memberByRole({courtId: t.data.cid, roleName: role}).then(
      function (content) {
        let result = update(content, {$apply: rs => {
          return rs.map(r=>{
            return update(r, {
              isLoading: {$set: true}
            })
          })
        }});
        switch (role) {
          case '单元长':
            t.data.voteResult.dyz = result;
            break;
          case '楼栋长':
            t.data.voteResult.ldz = result;
            break;
          case '委员':
            t.data.voteResult.wy = result;
            break;
          case '主任':
            t.data.voteResult.zr = result;
            break;
          default:
            break;
        }
        t.updateComponent();
        content.map(m => {
          t.getDoorById(m.doorplateId, role);
        })
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getDoorById(id, role) {
    let t = this;
    DB.ywh.doorById({id: id}).then(
      function (content) {
        switch (role) {
          case '单元长':
            t.data.voteResult.dyz = update(t.data.voteResult.dyz, {$apply: (dyzs) => {
              return dyzs.map(dyz => {
                if (dyz.doorplateId === id) {
                  return update(dyz, {
                    doorplateNo: {$set: content.doorplateNo},
                    building: {$set: content.building},
                    unit: {$set: content.unit},
                    isLoading: {$set: false}
                  });
                } else {
                  return update(dyz, {
                    isLoading: {$set: false}
                  });
                }
              })
            }});
            break;
          case '楼栋长':
            t.data.voteResult.ldz = update(t.data.voteResult.ldz, {$apply: (ldzs) => {
              return ldzs.map(ldz => {
                if (ldz.doorplateId === id) {
                  return update(ldz, {
                    doorplateNo: {$set: content.doorplateNo},
                    building: {$set: content.building},
                    unit: {$set: content.unit},
                    isLoading: {$set: false}
                  });
                } else {
                  return update(ldz, {
                    isLoading: {$set: false}
                  });
                }
              })
            }});
            break;
          case '委员':
            t.data.voteResult.wy = update(t.data.voteResult.wy, {$apply: (wys) => {
              return wys.map(wy => {
                if (wy.doorplateId === id) {
                  return update(wy, {
                    doorplateNo: {$set: content.doorplateNo},
                    building: {$set: content.building},
                    unit: {$set: content.unit},
                    isLoading: {$set: false}
                  });
                } else {
                  return update(wy, {
                    isLoading: {$set: false}
                  });
                }
              })
            }});
            break;
          case '主任':
            t.data.voteResult.zr = update(t.data.voteResult.zr, {$apply: (zrs) => {
              return zrs.map(zr => {
                if (zr.doorplateId === id) {
                  return update(zr, {
                    doorplateNo: {$set: content.doorplateNo},
                    building: {$set: content.building},
                    unit: {$set: content.unit},
                    isLoading: {$set: false}
                  });
                } else {
                  return update(zr, {
                    isLoading: {$set: false}
                  });
                }
              })
            }});
            break;
          default:
            break;
        }
        t.updateComponent();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getXjRwStatus(cid) {
    let t = this;
    DB.ywh.xjRwStatus({courtId: cid}).then(
      function (content) {
        t.data.rwStatus = content;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getCourtById(cid) {
    let t = this;
    DB.WechatAPI.getCourtById({id: cid}).then(
      function (content) {
        t.data.court = content;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getZr(courtId) {
    let t = this;
    DB.ywh.memberByRole({courtId: courtId, roleName: '主任'}).then(
      function (content) {
        if (content && content.length > 0) {
          t.data.zr = content[0];
          t.updateComponent();
          DB.WechatAPI.getProprietorById({id: t.data.zr.proprietorId}).then(
            function (content) {
              t.data.zr = update(t.data.zr, {
                p: {$set: content}
              });
              t.updateComponent();
            },
            function (error) {
              console.log(error);
            }
          );
        } else {
          t.data.zr = {};
          t.updateComponent();
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getProprietorById(id) {
    let t = this;
    DB.WechatAPI.getProprietorById({id: id}).then(
      function (content) {
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getWeiYuan(courtId) {
    let t = this;
    DB.ywh.memberByRole({courtId: courtId, roleName: '委员'}).then(
      function (content) {
        let nominations = [];
        if (content && content.length > 0) {
          content.map(d => {
            nominations.push({
              icon: API_URL + d.imageUrl,
              text: d.proprietorName,
              ...d,
            });
          })
        }
        t.data.nominations = nominations;
        t.updateComponent();
        nominations.map(nomination=>{
          t.getWyJobById(courtId, nomination.proprietorId);
        })
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getWeiYuanButZr(courtId) {
    let t = this;
    DB.ywh.memberByRoleButZr({courtId: courtId, roleName: '委员'}).then(
      function (content) {
        let nominations = [];
        if (content && content.length > 0) {
          content.map(d => {
            nominations.push({
              icon: API_URL + d.imageUrl,
              text: d.proprietorName,
              ...d,
            });
          })
        }
        t.data.nominations = nominations;
        t.updateComponent();
        nominations.map(nomination=>{
          t.getWyJobById(courtId, nomination.proprietorId);
        })
      },
      function (error) {
        console.log(error);
      }
    );
  },

  getWyJobById(cid, pid) {
    let t = this;
    DB.ywh.wyJobById({courtId: cid, proprietorId: pid}).then(
      function (content) {
        if (content && content.hasOwnProperty('roleId')) {
          DB.ywh.getRoleById({id: content.roleId}).then(
            function (content) {
              if (content) {
                t.data.nominations = update(t.data.nominations, {$apply: (nominations) => {
                  return nominations.map(nomination => {
                    if (nomination.courtId === cid && nomination.proprietorId === pid) {
                      return update(nomination, {
                        job: {$set: content.roleName}
                      })
                    }
                  })
                }});
                t.updateComponent();
              }
            },
            function (error) {
              console.log(error);
            }
          );
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  showModal(p) {
    this.data.modal = update(this.data.modal, {
      data: {$set: p}
    });
    this.data.modal = update(this.data.modal, {
      visible: {$set: true}
    });
    this.updateComponent();
  },

  onModalClose() {
    this.data.modal = update(this.data.modal, {
      visible: {$set: false},
    });
    this.updateComponent();
  },

  updateComponent() {
    this.trigger(this.data);
  },

  getInitialState() {
    return this.data;
  }
});
